package org.jeecg.modules.service;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.modules.wx.entity.WxAccount;
import org.jeecg.common.modules.wx.entity.WxUserinfo;
import org.jeecg.common.modules.wx.service.IWxAccountService;
import org.jeecg.common.modules.wx.service.IWxUserinfoService;
import org.jeecg.common.system.util.ApiJwtUtil;
import org.jeecg.common.util.ApiJwtVo;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.enums.BusinessTypeEnum;
import org.jeecg.common.util.tencent.SignUtil;
import org.jeecg.modules.config.CustomProperties;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.weixin4j.model.sns.SnsUser;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

/**
 * @author guoyh
 * @ClassName ApiWxUserInfoService
 * @Description
 * @since 2020/8/27 23:29
 **/
@Service
@Slf4j
public class ApiWxUserInfoService {

    @Resource
    private IWxUserinfoService wxUserinfoService;
    @Resource
    private IWxAccountService wxAccountService;
    @Resource
    private CustomProperties customProperties;
    @Resource
    private SignUtil signUtil;
    @Resource
    private RedisUtil redisUtil;

    public String login(SnsUser snsUser){
        WxAccount wxAccount = wxAccountService.getByAccountId(customProperties.getAccountId());
        WxUserinfo wxUserinfo = wxUserinfoService.getByOpenid(snsUser.getOpenid());
        if (Objects.isNull(wxUserinfo)){
            wxUserinfo = new WxUserinfo();
        }
        wxUserinfo.setWxAccountId(wxAccount.getId());
        BeanUtils.copyProperties(snsUser,wxUserinfo);
        wxUserinfo.setCreateTime(new Date());
        wxUserinfoService.saveOrUpdate(wxUserinfo);
        ApiJwtVo vo = new ApiJwtVo();
        vo.setBusinessId(wxUserinfo.getId());
        vo.setBusinessType(BusinessTypeEnum.PATIENT);
        String accessToken = ApiJwtUtil.sign(vo);

        //将token存储到redis中
        redisUtil.setNx(accessToken,'"'+snsUser.getOpenid()+'"',3600*24*7);
        return accessToken;
    }

    /**
     * 刷新IM Token
     * @param id
     * @return
     */
    public String refreshSign(String id){
        return signUtil.genUserSig(id,24 *30 * 60);
    }
}
